package com.example.hello.client.Button;

import com.example.hello.BootstrapButton;
import com.github.gwtbootstrap.client.ui.constants.ButtonType;
import com.github.gwtbootstrap.client.ui.resources.ButtonSize;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.MouseEventDetailsBuilder;
import com.vaadin.client.communication.RpcProxy;
import com.vaadin.client.communication.StateChangeEvent;
import com.vaadin.client.ui.AbstractComponentConnector;
import com.vaadin.shared.MouseEventDetails;
import com.vaadin.shared.ui.Connect;

@Connect(BootstrapButton.class)
public class BootstrapButtonConnector extends AbstractComponentConnector implements ClickHandler {

    private BootstrapButtonRpc rpc = RpcProxy.create(BootstrapButtonRpc.class, this);

    public BootstrapButtonConnector() {
        getWidget().addClickHandler(this);
    }

    @Override
    protected Widget createWidget() {
        return GWT.create(VBootstrapButton.class);
    }

    @Override
    public BootstrapButtonState getState() {
        return (BootstrapButtonState) super.getState();
    }

    @Override
    public VBootstrapButton getWidget() {
        return (VBootstrapButton) super.getWidget();
    }

    @Override
    public void onStateChanged(StateChangeEvent stateChangeEvent) {
        super.onStateChanged(stateChangeEvent);

        BootstrapButtonState state = getState();

        VBootstrapButton button = getWidget();

        button.setBlock(state.isBlock());
        button.setEnabled(state.isButtonEnabled());
        button.setSize(ButtonSize.valueOf(state.getSize()));
        button.setText(state.getText());
        button.setToggle(state.isToggle());
        button.setType(ButtonType.valueOf(state.getType()));
        button.clickShortcut = state.clickShortcutKeyCode;
    }

    @Override
    public void onClick(ClickEvent event) {
        MouseEventDetails details = MouseEventDetailsBuilder.buildMouseEventDetails(
                event.getNativeEvent(), getWidget().getElement());
        rpc.click(details);
    }

}